package com.jmu.edu.IMApplication.fragment;

import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.RefreshTagListEvent;
import com.jmu.edu.IMApplication.event.SwitchFragmentEvent;
import com.jmu.edu.IMApplication.net.bean.Tag;
import com.jmu.edu.IMApplication.net.bean.UserTag;
import com.jmu.edu.IMApplication.utils.ColorUtils;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class SelectTagFragment extends Fragment {
    private static final String TAG = "selectTag";
    private FlexboxLayout flexboxLayout;
    private TextView titleText, descriptionText;
    private MaterialButton changeButton, confirmButton;
    // 从数据库读取到的所有的tag
    private List<Tag> tagList;
    // 用来存储选中的checkedText
    private List<CheckedTextView> checkedTextViewList = new ArrayList<>();
    // 用来和tag组件userTag上传到数据库
    private String username;
    // tid - userTagId
    private Map<Integer, Integer> chosenUserTagMap;
    private String type;
    private String title;
    private String description;
    private int tagIndex = 0;

    public void setType(String type) {
        this.type = type;
    }

    public void setTitle(String title) {
        this.title = title;
        if (isAdded()) {
            titleText.setText(title);
        }
    }

    public void setChosenUserTagMap(Map<Integer, Integer> chosenUserTagMap) {
        this.chosenUserTagMap = chosenUserTagMap;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public SelectTagFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_select_tag, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();

    }

    private void initView() {
        changeButton = getView().findViewById(R.id.fragment_select_tag_change_button);
        confirmButton = getView().findViewById(R.id.fragment_select_tag_confirm);
        initListener();
        flexboxLayout = getView().findViewById(R.id.fragment_select_tag_flexBox);
        titleText = getView().findViewById(R.id.fragment_select_tag_title);
        descriptionText = getView().findViewById(R.id.fragment_select_tag_description);
        titleText.setText(title);
        descriptionText.setText(description);
        loadData();


    }

    private void loadData() {
        Request request = new Request.Builder().url(HttpUtil.URL_GET_ALL_TAG).get().build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                TypeToken<List<Tag>> typeToken = new TypeToken<List<Tag>>() {
                };
                tagList = new Gson().fromJson(json, typeToken.getType());
                // 进行下筛选处理，避免选取爱好的时候选取到生活习惯
                if (tagList != null) {
                    for (int i = 0; i < tagList.size(); i++) {
                        Tag tag = tagList.get(i);
                        //循环删除的时候需要考虑到下标和size变化的问题，所以需要i--
                        if (type.equals("hobby") && tag.getType() != 1) {
                            tagList.remove(i);
                            i--;
                        } else if (type.equals("habit") && tag.getType() != 2) {
                            tagList.remove(i);
                            i--;
                        } else if (type.equals("hatedHabit") && tag.getType() != 2) {
                            tagList.remove(i);
                            i--;
                        }

                    }
                }
                // 进行初始化
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkedTextViewList.isEmpty()) {
                            initTagData(0);
                        } else {
                            reloadTagData();
                        }

                    }
                });
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
        } else {
            tagIndex = 0;
            loadData();
        }
    }

    //初始化Tag标签存放的View
    private void initTagData(int startIndex) {
        for (tagIndex = startIndex; tagIndex < tagList.size(); tagIndex++) {
            View view = ViewUtils.getTagItemView(getLayoutInflater(), tagList.get(tagIndex).getTag(), tagIndex, getResources(), true);
            CheckedTextView checkedTextView = view.findViewById(R.id.item_tag_name);
            // 如果map中包含有该key，说明这个tag已经被选中了
            if (chosenUserTagMap.containsKey(tagList.get(tagIndex).getTagId())) {
                checkedTextView.callOnClick();
            }
            checkedTextViewList.add(checkedTextView);
            flexboxLayout.addView(view);
        }
    }

    private void reloadTagData() {
        for (int i = 0; i < checkedTextViewList.size(); i++) {
            //重置状态
            CheckedTextView checkedTextView = checkedTextViewList.get(i);
            checkedTextView.setVisibility(View.VISIBLE);
            if (checkedTextView.isChecked()) {
                checkedTextView.callOnClick();
            }
            //如果tagIndex还没有超出下标范围，说明还有tag可以展示
            if (tagIndex < tagList.size()) {
                checkedTextView.setText(tagList.get(tagIndex).getTag());
                if (chosenUserTagMap.containsKey(tagList.get(tagIndex).getTagId())) {
                    checkedTextView.callOnClick();
                }
                tagIndex++;
            } else {
                checkedTextView.setVisibility(View.GONE);
            }
        }
        // 如果checkedTextView的数量比tag数量还少，那么需要新增
        if (checkedTextViewList.size() < tagList.size()) {
            initTagData(tagIndex);
        }
    }

    private void initListener() {
        //确认按钮，点击后将数据更新到数据库，且返回上一个界面
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //目前暂时就只有打印数据+退出回退栈
                ArrayList<UserTag> checkedTagList = getCheckedTagList();
                //发送事件，该事件是刷新showTag界面的
                EventBus.getDefault().post(new RefreshTagListEvent(checkedTagList, type));
                // 遍历选中的userTag，删去原本就选中的userTag
                for (int i = 0; i < checkedTagList.size(); i++) {
                    UserTag tag = checkedTagList.get(i);
                    // 如果原本存在该tag，那么要删除
                    if (chosenUserTagMap.containsKey(tag.getTagId())) {
                        checkedTagList.remove(i);
                        i--;
                    }
                }
                //将这些userTag上传到服务器
                if (!checkedTagList.isEmpty()) {
                    RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(checkedTagList));
                    Request request = new Request.Builder().url(HttpUtil.URL_ADD_USER_TAG).post(requestBody).build();
                    MyApplication.getClient().newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e(TAG, "onFailure: ", e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Log.d(TAG, "onResponse: success");
                        }
                    });
                }


                //如果可以找到showTagFragment，说明showTagFragment已经被实例化过了，直接hide-show就好
                String tag = "showTag";
                ShowTagFragment showTagFragment = (ShowTagFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (showTagFragment == null) {
                    showTagFragment = new ShowTagFragment();
                }
                ViewUtils.hideFragment(SelectTagFragment.this, showTagFragment, tag, R.anim.from_left, R.anim.out_right);
            }
        });

    }


    /**
     * 获得被选中，且需要添加到数据库中的Tag
     *
     * @return tag的列表
     */
    public ArrayList<UserTag> getCheckedTagList() {
        ArrayList<UserTag> checkedTagList = new ArrayList<>();
        List<UserTag> removedUserTagList = new ArrayList<>();
        //这里循环用的是tagList，因为tagList才是实际上标签的数量，超过tagList的checkedTextView被设置为不可见
        for (int i = 0; i < tagList.size(); i++) {
            CheckedTextView checkedTextView = checkedTextViewList.get(i);
            if (checkedTextView.isChecked()) {
                Tag tag = tagList.get(i);
                UserTag userTag = new UserTag();
                userTag.setTag(tag.getTag());
                userTag.setTagId(tag.getTagId());
                userTag.setType(tag.getType());
                userTag.setUsername(username);
                if (type.equals("hatedHabit")) {
                    userTag.setLike(0);
                } else {
                    userTag.setLike(1);
                }
                checkedTagList.add(userTag);
                Log.d("标签选择界面", "选中:" + checkedTextView.getText().toString());
            } else {
                // 如果未选择的标签中，包含有key，说明之前被选中，现在放弃了，所以需要被删除
                if (chosenUserTagMap.containsKey(tagList.get(i).getTagId())) {
                    UserTag userTag = new UserTag();
                    userTag.setUserTagId(chosenUserTagMap.get(tagList.get(i).getTagId()));
                    removedUserTagList.add(userTag);
                }
                Log.d("标签选择界面", "未选中:" + checkedTextView.getText().toString());
            }
        }
        // removedUserTagList 是要删除的userTag, 这里要向服务器请求
        if (!removedUserTagList.isEmpty()) {
            RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(removedUserTagList));
            Request request = new Request.Builder().url(HttpUtil.URL_DEL_USER_TAG).post(requestBody).build();
            MyApplication.getClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: ", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, "onResponse: delete userTags success");
                }
            });
        }

        return checkedTagList;
    }

}